/* Copyright 2009 Requirements Management System
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.model.commons;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class DataSourceInformationProvider {
	private static final String FILE_NAME = "datasourceinformation.xml";
	private static final XStream xs = new XStream(new DomDriver("UTF-8"));
	
	public static void save(List<DataSourceInformation> all) {
		FileOutputStream fs = null;
		try {
			fs = new FileOutputStream(FILE_NAME);
			xs.toXML(all, fs);
		} catch(Exception e) {
			if(e instanceof RuntimeException)
				throw (RuntimeException)e;
			else
				throw new RuntimeException(e);
		} finally {
			try {
				if(fs!=null) {
					fs.flush();
					fs.close();
				}
			} catch(Exception _e) {/*IGNORE EXCEPTION*/}
		}		
	}
	@SuppressWarnings("unchecked")
	public static List<DataSourceInformation> getAll() {
		List<DataSourceInformation> all = new ArrayList<DataSourceInformation>();
		File file = new File(FILE_NAME);
		if(file.exists()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(FILE_NAME);
				all = (List<DataSourceInformation>)xs.fromXML(fis, all);
				return all;
			} catch (Exception e) {
				if(e instanceof RuntimeException)
					throw (RuntimeException)e;
				else
					throw new RuntimeException(e);
			} finally {
				try {
					if(fis!=null)
						fis.close();
				} catch(Exception _e) {/*IGNORE EXCEPTION*/}
			}
		} else {
			return all;
		}
	}
}
